package com.feihong.yw189.bluetooth.startreadcard;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import com.feihong.yw189.bluetooth.bleutils.BleGlobUtils;
import com.feihong.yw189.bluetooth.bleutils.BleHttpUtils;
import com.feihong.yw189.bluetooth.listener.UpLoadListener;
import com.ivsign.android.IDCReader.IDCReaderSDK;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;


/**
 * 华视读卡
 * 2017/8/24
 * 张鹏
 */
public class HuaShiConnectUtils {

    private UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private BluetoothSocket mBTHSocket = null;
    private BluetoothServerSocket mBThServer = null;
    private InputStream mmInStream = null;
    private OutputStream mmOutStream = null;
    private BluetoothDevice remoteDevice;
    private String bleAddress;
    private BluetoothAdapter ba;
    private Context context;
    private Activity mActivity;
    int Readflage = -99;
    private String bleName;

    private String name, sex, nation, id_num, address, sign_office, to, from, born;
    private String birth_year, birth_month, birth_day, sign_data, photoHeard;
    private Bitmap photo;
    private String bluetoothName = "";
    String[] decodeInfo = new String[10];
    private BleHttpUtils bleHttpUtils;
    private Boolean mFlag = false;
    // 注册成功失败监听
    private UpLoadListener mOnUpLoadListener;

    public HuaShiConnectUtils(Context context, BluetoothAdapter ba, BluetoothDevice remoteDevice,
                               String bleName,   String bleAddress,  final String bluetoothName,
                              Boolean flag, final UpLoadListener mOnUpLoadListener) {
        this.context = context;
        this.mActivity = (Activity) context;
        this.ba = ba;
        this.remoteDevice = remoteDevice;
        this.bleName = bleName;
        this.bleAddress = bleAddress;
        this.mFlag = flag;
        this.bluetoothName = bluetoothName;
        this.mOnUpLoadListener = mOnUpLoadListener;
        bleHttpUtils = new BleHttpUtils(context, bluetoothName, mFlag, new UpLoadListener() {
            @Override
            public void onSucUpLoad(String bluetoohName, String address, String sex, String id_num,
                                    String nation, String sign_office, String name, String sign_data,
                                    String birth_year, String birth_month, String birth_day,
                                    Bitmap photo, String filePhoto, String idPath, String to,
                                    String from, String born, String photoHeard) {
                mOnUpLoadListener.onSucUpLoad(bluetoothName, address, sex, id_num, nation,
                        sign_office, name, sign_data, birth_year, birth_month, birth_day,
                        photo, filePhoto, idPath, to,
                        from, born, photoHeard);
                // 读卡成功需要断开连接
                stopConnect();
            }

            @Override
            public void onErrUpLoad(String err) {
                mOnUpLoadListener.onErrUpLoad(err);
                // 读卡失败需要断开连接
                stopConnect();
            }
        });
    }

    /**
     * 连接
     */
    public void connect() {

        try {
            Intent discoverableIntent = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//使得蓝牙处于可发现模式，持续时间150s
            discoverableIntent.putExtra(
                    BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 150);
            mBTHSocket = remoteDevice.createRfcommSocketToServiceRecord(MY_UUID);
            int sdk = Integer.parseInt(Build.VERSION.SDK);
            if (sdk >= 10) {
                mBTHSocket = remoteDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID);
            } else {
                mBTHSocket = remoteDevice.createRfcommSocketToServiceRecord(MY_UUID);
            }
            mBThServer = ba.listenUsingRfcommWithServiceRecord("myServerSocket", MY_UUID);
            mBTHSocket.connect();
            mmInStream = mBTHSocket.getInputStream();
            mmOutStream = mBTHSocket.getOutputStream();
            if ((mmInStream != null) && (mmOutStream != null)) {
                HsBlueToolsRead();
            } else {
                mOnUpLoadListener.onErrUpLoad("设备连接失败");
            }
        } catch (IOException e) {
            mOnUpLoadListener.onErrUpLoad("设备连接失败:" + e.toString());
        }
    }


    /**
     * 华视的关闭状态
     */
    public void stopConnect() {

        try {
            if ((mmInStream == null) || (mmInStream == null)
                    || mBTHSocket == null || mBThServer == null) {
                return;
            }
            mmOutStream.close();
            mmInStream.close();
            mBTHSocket.close();
            mBThServer.close();
        } catch (Exception e) {
            Log.e("项目异常", "------断开连接异常------" + e.toString());
            mOnUpLoadListener.onErrUpLoad("");
            e.printStackTrace();
        }
        Log.e("项目异常华视", "------华视断开连接------");

    }

    /**
     * 华视读卡
     */
    private void HsBlueToolsRead() {
        int readcount = 15;
        try {
            while (readcount > 1) {
                HsReadCard();
                readcount = readcount - 1;
                if (Readflage > 0) {
                    readcount = 0;
                    if (Readflage == 1) {
                        FileInputStream fis = new FileInputStream
                                (Environment.getExternalStorageDirectory() + "/wltlib/zp.bmp");
                        // 身份证头像
                        photo = BitmapFactory.decodeStream(fis);
                        photoHeard = BleGlobUtils.replaceBlank(
                                BleGlobUtils.bitmapToBase64(photo));
                        name = decodeInfo[0]; //姓名
                        sex = decodeInfo[1];//性别
                        nation = decodeInfo[2];//民族
                        born = decodeInfo[3].substring(0, 4) + decodeInfo[3].substring(4, 6)
                                + decodeInfo[3].substring(6, 8);
                        birth_year = decodeInfo[3].substring(0, 4);
                        birth_month = decodeInfo[3].substring(4, 6);
                        birth_day = decodeInfo[3].substring(6, 8);

                        address = decodeInfo[4];//地址
                        id_num = decodeInfo[5];  //身份证号
                        sign_office = decodeInfo[6];  //签发机关

                        from = decodeInfo[7].substring(0, 4) +
                                decodeInfo[7].substring(4, 6) +
                                decodeInfo[7].substring(6, 8);

                        if (decodeInfo[8].contains("长期")) {
                            sign_data = decodeInfo[7].substring(0, 4)
                                    + "." + decodeInfo[7].substring(4, 6) + "." +
                                    decodeInfo[7].substring(6, 8) + "--" +
                                    decodeInfo[8].trim();
                            to = "长期";
                        } else {
                            to = decodeInfo[8].substring(0, 4) +
                                    decodeInfo[8].substring(4, 6) +
                                    decodeInfo[8].substring(6, 8);
                            sign_data = decodeInfo[7].substring(0, 4)
                                    + "." + decodeInfo[7].substring(4, 6) + "." +
                                    decodeInfo[7].substring(6, 8) + "--" +
                                    decodeInfo[8].substring(0, 4) + "."
                                    + decodeInfo[8].substring(4, 6) + "." +
                                    decodeInfo[8].substring(6, 8);
                        }
                        Log.e("项目异常", name + "------1------" + id_num);
                        bleHttpUtils.upLoadSfzPhoto(bleName,bleAddress,address, photoHeard, sex, id_num, nation,
                                sign_office, to, name, from, born, sign_data, birth_year,
                                birth_month, birth_day, photo);
                        fis.close();
                    } else {
                        mOnUpLoadListener.onErrUpLoad("照片解码异常");
                        return;
                    }
                } else {
                    if (Readflage == -2) {
                        mOnUpLoadListener.onErrUpLoad("蓝牙连接异常");
                    } else if (Readflage == -3) {
                        mOnUpLoadListener.onErrUpLoad("寻卡失败");
                    } else if (Readflage == -4) {
                        mOnUpLoadListener.onErrUpLoad("选卡失败");
                    } else if (Readflage == -5) {
                        mOnUpLoadListener.onErrUpLoad("读卡失败");
                    } else if (Readflage == -99) {
                        mOnUpLoadListener.onErrUpLoad("操作异常");
                    }
                    return;
                }
                Thread.sleep(100);
            }
        } catch (Exception e) {
            mOnUpLoadListener.onErrUpLoad("读取数据异常:" + e.toString());
        }
    }

    byte[] cmd_find = {(byte) 0xAA, (byte) 0xAA, (byte) 0xAA, (byte) 0x96, 0x69, 0x00, 0x03, 0x20, 0x01, 0x22};
    byte[] cmd_selt = {(byte) 0xAA, (byte) 0xAA, (byte) 0xAA, (byte) 0x96, 0x69, 0x00, 0x03, 0x20, 0x02, 0x21};
    byte[] cmd_read = {(byte) 0xAA, (byte) 0xAA, (byte) 0xAA, (byte) 0x96, 0x69, 0x00, 0x03, 0x30, 0x01, 0x32};
    byte[] recData = new byte[1500];

    /**
     * 华视  读卡
     */
    private void HsReadCard() {
        try {
            if ((mmInStream == null) || (mmOutStream == null)) {
                Readflage = -2;//连接异常
                return;
            }
            mmOutStream.write(cmd_find);
            Thread.sleep(200);
            int datalen = mmInStream.read(recData);
            if (recData[9] == -97) {
                mmOutStream.write(cmd_selt);
                Thread.sleep(200);
                datalen = mmInStream.read(recData);
                if (recData[9] == -112) {
                    mmOutStream.write(cmd_read);
                    Thread.sleep(1000);
                    byte[] tempData = new byte[1500];
                    if (mmInStream.available() > 0) {
                        datalen = mmInStream.read(tempData);
                    } else {
                        Thread.sleep(500);
                        if (mmInStream.available() > 0) {
                            datalen = mmInStream.read(tempData);
                        }
                    }
                    int flag = 0;
                    if (datalen < 1294) {
                        for (int i = 0; i < datalen; i++, flag++) {
                            recData[flag] = tempData[i];
                        }
                        Thread.sleep(1000);
                        if (mmInStream.available() > 0) {
                            datalen = mmInStream.read(tempData);
                        } else {
                            Thread.sleep(500);
                            if (mmInStream.available() > 0) {
                                datalen = mmInStream.read(tempData);
                            }
                        }
                        for (int i = 0; i < datalen; i++, flag++) {
                            recData[flag] = tempData[i];
                        }
                    } else {
                        for (int i = 0; i < datalen; i++, flag++) {
                            recData[flag] = tempData[i];
                        }
                    }
                    tempData = null;
                    if (flag == 1295) {
                        if (recData[9] == -112) {
                            byte[] dataBuf = new byte[256];
                            for (int i = 0; i < 256; i++) {
                                dataBuf[i] = recData[14 + i];
                            }
                            String TmpStr = new String(dataBuf, "UTF-16LE");
                            TmpStr = new String(TmpStr.getBytes("UTF-8"));
                            decodeInfo[0] = TmpStr.substring(0, 15);
                            decodeInfo[1] = TmpStr.substring(15, 16);
                            decodeInfo[2] = TmpStr.substring(16, 18);
                            decodeInfo[3] = TmpStr.substring(18, 26);
                            decodeInfo[4] = TmpStr.substring(26, 61);
                            decodeInfo[5] = TmpStr.substring(61, 79);
                            decodeInfo[6] = TmpStr.substring(79, 94);
                            decodeInfo[7] = TmpStr.substring(94, 102);
                            decodeInfo[8] = TmpStr.substring(102, 110);
                            decodeInfo[9] = TmpStr.substring(110, 128);
                            if (decodeInfo[1].equals("1"))
                                decodeInfo[1] = "男";
                            else
                                decodeInfo[1] = "女";
                            try {
                                int code = Integer.parseInt(decodeInfo[2].toString());
                                decodeInfo[2] = decodeNation(code);
                            } catch (Exception e) {
                                decodeInfo[2] = "";
                            }
                            //照片解码
                            try {
                                int ret = IDCReaderSDK.Init();//华视好多机型返回-1
                                if (ret == 0) {
                                    byte[] datawlt = new byte[1384];
                                    byte[] byLicData = {(byte) 0x05, (byte) 0x00, (byte) 0x01,
                                            (byte) 0x00, (byte) 0x5B, (byte) 0x03, (byte) 0x33,
                                            (byte) 0x01, (byte) 0x5A, (byte) 0xB3, (byte) 0x1E,
                                            (byte) 0x00};
                                    for (int i = 0; i < 1295; i++) {
                                        datawlt[i] = recData[i];
                                    }
                                    int t = IDCReaderSDK.unpack(datawlt, byLicData);
                                    if (t == 1) {
                                        Readflage = 1;//读卡成功
                                    } else {
                                        Readflage = 6;//照片解码异常
                                    }
                                } else {
                                    Readflage = 6;//照片解码异常
                                }
                            } catch (Exception e) {
                                Readflage = 6;//照片解码异常
                            }

                        } else {
                            Readflage = -5;//读卡失败！
                        }
                    } else {
                        Readflage = -5;//读卡失败
                    }
                } else {
                    Readflage = -4;//选卡失败
                }
            } else {
                Readflage = -3;//寻卡失败
            }
        } catch (IOException e) {
            Readflage = -99;//读取数据异常
        } catch (InterruptedException e) {
            Readflage = -99;//读取数据异常
        }
    }

    /**
     * 华视 所需
     */
    private String decodeNation(int code) {
        String nation;
        switch (code) {
            case 1:
                nation = "汉";
                break;
            case 2:
                nation = "蒙古";
                break;
            case 3:
                nation = "回";
                break;
            case 4:
                nation = "藏";
                break;
            case 5:
                nation = "维吾尔";
                break;
            case 6:
                nation = "苗";
                break;
            case 7:
                nation = "彝";
                break;
            case 8:
                nation = "壮";
                break;
            case 9:
                nation = "布依";
                break;
            case 10:
                nation = "朝鲜";
                break;
            case 11:
                nation = "满";
                break;
            case 12:
                nation = "侗";
                break;
            case 13:
                nation = "瑶";
                break;
            case 14:
                nation = "白";
                break;
            case 15:
                nation = "土家";
                break;
            case 16:
                nation = "哈尼";
                break;
            case 17:
                nation = "哈萨克";
                break;
            case 18:
                nation = "傣";
                break;
            case 19:
                nation = "黎";
                break;
            case 20:
                nation = "傈僳";
                break;
            case 21:
                nation = "佤";
                break;
            case 22:
                nation = "畲";
                break;
            case 23:
                nation = "高山";
                break;
            case 24:
                nation = "拉祜";
                break;
            case 25:
                nation = "水";
                break;
            case 26:
                nation = "东乡";
                break;
            case 27:
                nation = "纳西";
                break;
            case 28:
                nation = "景颇";
                break;
            case 29:
                nation = "柯尔克孜";
                break;
            case 30:
                nation = "土";
                break;
            case 31:
                nation = "达斡尔";
                break;
            case 32:
                nation = "仫佬";
                break;
            case 33:
                nation = "羌";
                break;
            case 34:
                nation = "布朗";
                break;
            case 35:
                nation = "撒拉";
                break;
            case 36:
                nation = "毛南";
                break;
            case 37:
                nation = "仡佬";
                break;
            case 38:
                nation = "锡伯";
                break;
            case 39:
                nation = "阿昌";
                break;
            case 40:
                nation = "普米";
                break;
            case 41:
                nation = "塔吉克";
                break;
            case 42:
                nation = "怒";
                break;
            case 43:
                nation = "乌孜别克";
                break;
            case 44:
                nation = "俄罗斯";
                break;
            case 45:
                nation = "鄂温克";
                break;
            case 46:
                nation = "德昂";
                break;
            case 47:
                nation = "保安";
                break;
            case 48:
                nation = "裕固";
                break;
            case 49:
                nation = "京";
                break;
            case 50:
                nation = "塔塔尔";
                break;
            case 51:
                nation = "独龙";
                break;
            case 52:
                nation = "鄂伦春";
                break;
            case 53:
                nation = "赫哲";
                break;
            case 54:
                nation = "门巴";
                break;
            case 55:
                nation = "珞巴";
                break;
            case 56:
                nation = "基诺";
                break;
            case 97:
                nation = "其他";
                break;
            case 98:
                nation = "外国血统中国籍人士";
                break;
            default:
                nation = "";
                break;
        }
        return nation;
    }


}
